import sqlite3
from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from MainDesign import Ui_MdiArea


import pygame
import sys
import time

import classes.myplane as myplane#我方飞机类
import classes.supply as supply#补给类
import classes.bullet as bullet#子弹类
import classes.enemy as enemy#敌人类

import utils.add_enemy as add_enemy
import utils.functions as util_function

from pygame.locals import *
from random import *



class MyPyQT_Form(QtWidgets.QWidget, Ui_MdiArea):
    def __init__(self):
        super(MyPyQT_Form, self).__init__()
        self.setupUi(self)

        pygame.init()  # 初始化pygame
        pygame.mixer.init()  # 初始化混音模块

        self.dbname = "GameRecord.db"
        self.conn = sqlite3.connect(self.dbname)
        self.conn.execute("create table if not exists user(id integer primary key autoincrement, username varchar(128), password varchar(128))")
        self.conn.execute("create table if not exists scores(id integer primary key autoincrement, username varchar(128), mode varchar(128),score integer, duration integer)")
        self.cursor = self.conn.cursor()


        self.LoginWindow.setFixedSize(360,640)
        self.RegisterWindow.setFixedSize(360,640)
        self.WelcomeWindow.setFixedSize(360,640)
        self.SettingWindow.setFixedSize(360,640)
        self.RankingWindow.setFixedSize(360,640)
        self.GameWindow.setFixedSize(360,640)
        #self.windows = [self.LoginWindow,self.RegisterWindow,self.WelcomeWindow,self.SettingWindow,self.RankingWindow,self.GameWindow]
        #center(self.windows)


        #游戏设置
        self.sound_status = 'on'#游戏声音 开或者关 on or off
        self.sound_status2 = 'on'#游戏音效 开或者关 on or off

        self.game_modes = ['easy','medium','hard']
        self.game_mode = self.game_modes[0]#游戏难度 简单或者中等或者难 easy or medium or hard

        #设置默认音量
        self.background_music_volume = 0.3
        self.game_sound_volume = 0.3

        # 载入游戏音乐
        self.background_music = pygame.mixer.Sound("resources/sounds/game_music.ogg")
        self.bullet_sound = pygame.mixer.Sound("resources/sounds/bullet.wav")
        self.bomb_sound = pygame.mixer.Sound("resources/sounds/use_bomb.wav")
        self.supply_sound = pygame.mixer.Sound("resources/sounds/supply.wav")
        self.get_bomb_sound = pygame.mixer.Sound("resources/sounds/get_bomb.wav")
        self.get_bullet_sound = pygame.mixer.Sound("resources/sounds/get_bullet.wav")
        self.upgrade_sound = pygame.mixer.Sound("resources/sounds/upgrade.wav")
        self.enemy3_fly_sound = pygame.mixer.Sound("resources/sounds/enemy3_flying.wav")
        self.enemy1_down_sound = pygame.mixer.Sound("resources/sounds/enemy1_down.wav")
        self.enemy2_down_sound = pygame.mixer.Sound("resources/sounds/enemy2_down.wav")
        self.enemy3_down_sound = pygame.mixer.Sound("resources/sounds/enemy3_down.wav")
        self.me_down_sound = pygame.mixer.Sound("resources/sounds/me_down.wav")


        #记录当前用户
        self.localuser = None

    def login(self):

        username = self.UserNameInput.text()
        userpassword = self.UserPaswordInput.text()
        if len(username)==0 or len(userpassword)==0:
            QMessageBox.warning(self, '提示', '请将信息填写完整！', QMessageBox.Ok)
        else:
            #查找数据库内的用户信息
            self.userdata = self.cursor.execute("select * from user where username='%s'" % username).fetchone()
            if self.userdata:
                self.userdata = list(self.userdata)
                #核对密码
                if self.userdata[2] == userpassword:
                    self.localuser = username
                    QMessageBox.information(self, '登陆成功', '欢迎你！'+str(self.localuser), QMessageBox.Ok)
                    self.LoginWindow.hide()
                    self.WelcomeWindow.raise_()
                    self.WelcomeWindow.show()
                else:
                    QMessageBox.warning(self, '登录失败', '请核对密码或者联系管理员！', QMessageBox.Ok)
            else:
                QMessageBox.warning(self, '登录失败', '未查找到该用户！', QMessageBox.Ok)

    def go_to_register(self):
            #QMessageBox.information(self, '提示', '正在重定向至注册界面！', QMessageBox.Ok)
            self.LoginWindow.hide()
            self.RegisterWindow.show()

    def register(self):

        # 得到用户输入的帐号，密码
        username = self.RegisterUserNameInput.text()
        userpassword = self.RegisterUserPasswordInput.text()

        # # 有部分信息未填
        if not username or not userpassword :
            QMessageBox.warning(self, '注册失败', '请将信息填写完整！', QMessageBox.Ok)
            return
        print(username, userpassword)

        # # 检测帐号重复
        data = self.cursor.execute("select * from user where username='%s'" % username).fetchone()
        print(data)
        if data:
            QMessageBox.warning(self, '注册失败', '账号已存在，请重新输入！', QMessageBox.Ok)
            return

        # 写入用户信息到数据库
        self.cursor.execute("insert into user (username,password) VALUES (?,?)",(username,userpassword))

        #数据库修改提交
        self.conn.commit()
        QMessageBox.information(self, '注册成功', '请用注册的账号登录！', QMessageBox.Ok)

        #将文本框置空
        self.RegisterUserNameInput.setText("")
        self.RegisterUserPasswordInput.setText("")
        #切换登录窗口
        self.RegisterWindow.hide()
        self.LoginWindow.show()

    def go_to_login(self):
        self.RegisterWindow.hide()
        self.LoginWindow.show()
        self.LoginWindow.raise_()

    def game_exit(self):
        sys.exit(app.exec_())

    ##以下是游戏功能的实现
    def start_game(self):

        pygame.init()  # 初始化pygame
        pygame.mixer.init()  # 初始化混音模块

        if self.sound_status =='on':#背景音乐打开
            self.background_music.set_volume(self.background_music_volume)
            self.background_music.play(loops=-1)
        else:
            self.background_music_volume = 0

        if self.sound_status2 =='on':#游戏音效打开，设置为预选音量w
            self.bullet_sound.set_volume(self.game_sound_volume)
            self.bomb_sound.set_volume(self.game_sound_volume)
            self.supply_sound.set_volume(self.game_sound_volume)
            self.get_bomb_sound.set_volume(self.game_sound_volume)
            self.get_bullet_sound.set_volume(self.game_sound_volume)
            self.upgrade_sound.set_volume(self.game_sound_volume)
            self.enemy3_fly_sound.set_volume(self.game_sound_volume)
            self.enemy1_down_sound.set_volume(self.game_sound_volume)
            self.enemy2_down_sound.set_volume(self.game_sound_volume)
            self.enemy3_down_sound.set_volume(self.game_sound_volume)
            self.me_down_sound.set_volume(self.game_sound_volume)
        else:
            self.game_sound_volume = 0#将音量设置为0
            self.bullet_sound.set_volume(self.game_sound_volume)
            self.bomb_sound.set_volume(self.game_sound_volume)
            self.supply_sound.set_volume(self.game_sound_volume)
            self.get_bomb_sound.set_volume(self.game_sound_volume)
            self.get_bullet_sound.set_volume(self.game_sound_volume)
            self.upgrade_sound.set_volume(self.game_sound_volume)
            self.enemy3_fly_sound.set_volume(self.game_sound_volume)
            self.enemy1_down_sound.set_volume(self.game_sound_volume)
            self.enemy2_down_sound.set_volume(self.game_sound_volume)
            self.enemy3_down_sound.set_volume(self.game_sound_volume)
            self.me_down_sound.set_volume(self.game_sound_volume)

        self.WelcomeWindow.hide()#隐藏欢迎窗口

        bg_size = width, height = 540, 960  # 游戏界面大小

        screen = pygame.display.set_mode(bg_size)
        pygame.display.set_caption("飞机大战")

        background = pygame.image.load("resources/images/background1.png").convert()  # 导入背景图片
        # 使用 convert 可以转换格式，提高 blit 的速度
        # 其中 convert_alpha相对于convert，保留了图像的Alpha 通道信息，可以认为是保留了透明的部分，实现了透明转换

        BLACK = (0, 0, 0)
        WHITE = (255, 255, 255)
        GREEN = (0, 255, 0)
        RED = (255, 0, 0)

        def gaming():

            game_time_start = time.time()  # 开始计时
            # 生成我方飞机
            me = myplane.MyPlane(bg_size)
            #生成敌方飞机
            enemies = pygame.sprite.Group()

            # 生成敌方小型飞机
            small_enemies = pygame.sprite.Group()
            add_enemy.add_small_enemies(small_enemies, enemies,15,bg_size)

            # 生成敌方中型飞机
            mid_enemies = pygame.sprite.Group()
            add_enemy.add_mid_enemies(mid_enemies, enemies, 4,bg_size)

            # 生成敌方大型飞机
            big_enemies = pygame.sprite.Group()
            add_enemy.add_big_enemies(big_enemies, enemies, 2,bg_size)

            # 生成普通子弹
            bullet1 = []
            bullet1_index = 0
            BULLET1_NUM = 16
            for i in range(BULLET1_NUM):
                bullet1.append(bullet.Bullet1(me.rect.midtop))
            # me.rect.midtop正中间

            # 生成超级子弹
            bullet2 = []
            bullet2_index = 0
            BULLET2_NUM = 12
            for i in range(BULLET2_NUM // 2):
                bullet2.append(bullet.Bullet2((me.rect.centerx - 33, me.rect.centery)))
                bullet2.append(bullet.Bullet2((me.rect.centerx + 30, me.rect.centery)))

            # 落在两侧的机翼上

            # 帧的刷新速率，使动画能够以一个平稳的速率运行
            clock = pygame.time.Clock()

            # 中弹图片索引
            e1_destroy_index = 0
            e2_destroy_index = 0
            e3_destroy_index = 0
            me_destroy_index = 0

            # 统计得分
            score = 0
            score_font = pygame.font.Font("resources/font/font.ttf", 36)

            # 标志是否暂停游戏
            paused = False
            #暂停键没被按住和按住
            pause_nor_image = pygame.image.load("resources/images/pause_nor.png").convert_alpha()
            pause_pressed_image = pygame.image.load("resources/images/pause_pressed.png").convert_alpha()
            # 恢复键没被按住和按住
            resume_nor_image = pygame.image.load("resources/images/resume_nor.png").convert_alpha()
            resume_pressed_image = pygame.image.load("resources/images/resume_pressed.png").convert_alpha()
            # 设置暂停键位置
            paused_rect = pause_nor_image.get_rect()
            paused_rect.left, paused_rect.top = width - paused_rect.width - 10, 10
            paused_image = pause_nor_image

            # 全屏炸弹
            bomb_image = pygame.image.load("resources/images/bomb.png").convert_alpha()
            bomb_rect = bomb_image.get_rect()
            bomb_font = pygame.font.Font("resources/font/font.ttf", 48)
            bomb_num = 3

            # 生命数量
            life_image = pygame.image.load("resources/images/life.png").convert_alpha()
            life_rect = life_image.get_rect()
            life_num = 1

            # 游戏结束画面资源导入
            gameover_font = pygame.font.Font("resources/font/font.TTF", 48)
            again_image = pygame.image.load("resources/images/again.png").convert_alpha()
            again_rect = again_image.get_rect()
            gameover_image = pygame.image.load("resources/images/gameover.png").convert_alpha()
            gameover_rect = gameover_image.get_rect()


            # Pygame通过事件队列控制所有的时间消息,该模块中的程序将帮助管理事件队列
            # 使用pygame.USEREVENT创建多个用户事件只需要将该常量加1即可：

            # 每30秒发放一个补给包
            bullet_supply = supply.Bullet_Supply(bg_size)#子弹补给包
            bomb_supply = supply.Bomb_Supply(bg_size)#炸弹补给包

            SUPPLY_TIME = USEREVENT#创建补给时间的用户事件
            pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)

            # 超级子弹定时器 用户事件
            DOUBLE_BULLET_TIME = USEREVENT + 1

            # 标志是否使用超级子弹
            is_double_bullet = False

            # 解除我方无敌状态定时器 用户事件
            INVINCIBLE_TIME = USEREVENT + 2

            # 用于阻止重复打开记录文件
            recorded = False

            # 用于切换图片
            switch_image = True
            # 用于延迟
            delay = 100
            level = 1

            # 根据用户选择的模式设置不同的难度级别
            set_game_mode = False
            if self.game_mode=='easy':
                game_level_mode = 1
                print(self.game_mode,level)
            elif self.game_mode=='medium':
                game_level_mode = 2
                print(self.game_mode, level)
            else:
                game_level_mode = 3
                print(self.game_mode, level)

            running = True

            #程序运行核心
            while running:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        pygame.quit()
                        self.WelcomeWindow.show()

                    elif event.type == MOUSEBUTTONDOWN:
                        if event.button == 1 and paused_rect.collidepoint(event.pos):#鼠标左键点击，同时包含在暂停键内
                            paused = not paused#
                            if paused:
                                pygame.time.set_timer(SUPPLY_TIME, 0)#关闭补给定时器
                                pygame.mixer.music.pause()
                                pygame.mixer.pause()
                            else:
                                pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)  #恢复补给定时器
                                pygame.mixer.music.unpause()
                                pygame.mixer.unpause()

                    elif event.type == MOUSEMOTION:#鼠标移动
                        if paused_rect.collidepoint(event.pos):#鼠标移动到暂停键上但是没有按下
                            if paused:
                                paused_image = resume_pressed_image#图标做相应的改变
                            else:
                                paused_image = pause_pressed_image
                        else:
                            if paused:
                                paused_image = resume_nor_image
                            else:
                                paused_image = pause_nor_image

                    elif event.type == KEYDOWN:#按下按键
                        if event.key == K_SPACE:  # 按下空格键
                            if bomb_num:#炸弹数量还有多余
                                bomb_num -= 1
                                self.bomb_sound.play()
                                for each in enemies:#清除屏幕上存在的所有飞机
                                    if each.rect.bottom > 0:
                                        each.active = False

                    # 自定义的用户事件
                    # 随机选择掉落的补给
                    elif event.type == SUPPLY_TIME:
                        self.supply_sound.play()
                        if choice([True, False]):#随机选择补给
                            bomb_supply.reset()#炸弹补给重置
                        else:
                            bullet_supply.reset()#子弹补给重置

                    elif event.type == DOUBLE_BULLET_TIME:#超级子弹事件
                        is_double_bullet = False#禁用超级子弹状态
                        pygame.time.set_timer(DOUBLE_BULLET_TIME, 0)#关闭超级子弹计时器

                    elif event.type == INVINCIBLE_TIME:#无敌事件
                        me.invincible = False#禁用无敌状态
                        pygame.time.set_timer(INVINCIBLE_TIME, 0)#关闭无敌状态计时器

                #修改难度


                if  set_game_mode==False:#增加敌机数量和难度
                    if game_level_mode== 2:
                        # 增加3架小型敌机、2架中型敌机和1架大型敌机
                        add_enemy.add_small_enemies(small_enemies, enemies, 3,bg_size)
                        add_enemy.add_mid_enemies(mid_enemies, enemies, 2,bg_size)
                        add_enemy.add_big_enemies(big_enemies, enemies, 1,bg_size)
                        util_function.inc_speed(small_enemies, 1)
                        util_function.inc_speed(mid_enemies, 1)
                        set_game_mode = True
                        print('enhance2')
                    elif game_level_mode==3:
                        add_enemy.add_small_enemies(small_enemies, enemies, 3, bg_size)
                        add_enemy.add_mid_enemies(mid_enemies, enemies, 2, bg_size)
                        add_enemy.add_big_enemies(big_enemies, enemies, 1, bg_size)
                        util_function.inc_speed(small_enemies, 1)
                        util_function.inc_speed(mid_enemies, 1)
                        set_game_mode = True
                        print('enhance3')
                        # 提升小型敌机的速度

                # 根据用户的得分增加难度
                if level == 1 and score > 5000:
                    level = 2
                    set_game_mode = False
                    self.upgrade_sound.play()
                    # 增加3架小型敌机、2架中型敌机和1架大型敌机
                    add_enemy.add_small_enemies(small_enemies, enemies, 3,bg_size)
                    add_enemy.add_mid_enemies(mid_enemies, enemies, 2,bg_size)
                    add_enemy.add_big_enemies(big_enemies, enemies, 1,bg_size)
                    # 提升小型敌机的速度
                    util_function.inc_speed(small_enemies, 1)
                elif level == 2 and score > 30000:
                    level = 3
                    set_game_mode = False
                    self.upgrade_sound.play()
                    # 增加5架小型敌机、3架中型敌机和2架大型敌机
                    add_enemy.add_small_enemies(small_enemies, enemies, 5,bg_size)
                    add_enemy.add_mid_enemies(mid_enemies, enemies, 3,bg_size)
                    add_enemy.add_big_enemies(big_enemies, enemies, 2,bg_size)
                    # 提升小型敌机的速度
                    util_function.inc_speed(small_enemies, 1)
                    util_function.inc_speed(mid_enemies, 1)
                elif level == 3 and score > 60000:
                    level = 4
                    set_game_mode = False
                    self.upgrade_sound.play()
                    # 增加5架小型敌机、3架中型敌机和2架大型敌机
                    add_enemy.add_small_enemies(small_enemies, enemies, 5,bg_size)
                    add_enemy.add_mid_enemies(mid_enemies, enemies, 3,bg_size)
                    add_enemy.add_big_enemies(big_enemies, enemies, 2,bg_size)
                    # 提升小型敌机的速度
                    util_function.inc_speed(small_enemies, 1)
                    util_function.inc_speed(mid_enemies, 1)
                elif level == 4 and score > 100000:
                    level = 5
                    set_game_mode = False
                    self.upgrade_sound.play()
                    # 增加5架小型敌机、3架中型敌机和2架大型敌机
                    add_enemy.add_small_enemies(small_enemies, enemies, 5,bg_size)
                    add_enemy.add_mid_enemies(mid_enemies, enemies, 3,bg_size)
                    add_enemy.add_big_enemies(big_enemies, enemies, 2,bg_size)
                    # 提升小型敌机的速度
                    util_function.inc_speed(small_enemies, 1)
                    util_function.inc_speed(mid_enemies, 1)


                #以上是运行基本设置
                # 刷新页面
                screen.blit(background, (0, 0))

                if life_num and not paused:
                    # 检测用户的方向键操作，并控制飞机往对应方向进行移动
                    key_pressed = pygame.key.get_pressed()

                    if key_pressed[K_w] or key_pressed[K_UP]:
                        me.moveUp()
                    if key_pressed[K_s] or key_pressed[K_DOWN]:
                        me.moveDown()
                    if key_pressed[K_a] or key_pressed[K_LEFT]:
                        me.moveLeft()
                    if key_pressed[K_d] or key_pressed[K_RIGHT]:
                        me.moveRight()

                    # 绘制全屏炸弹补给并检测是否获得
                    if bomb_supply.active:
                        bomb_supply.move()#补给移动
                        screen.blit(bomb_supply.image, bomb_supply.rect)#刷新补给位置
                        if pygame.sprite.collide_mask(bomb_supply, me):#补给和飞机相撞
                            self.get_bomb_sound.play()
                            if bomb_num < 3:
                                bomb_num += 1
                            bomb_supply.active = False

                    # 绘制超级子弹补给并检测是否获得
                    if bullet_supply.active:
                        bullet_supply.move()#补给移动
                        screen.blit(bullet_supply.image, bullet_supply.rect)#刷新补给位置
                        if pygame.sprite.collide_mask(bullet_supply, me):#补给和飞机相撞，获得超级子弹
                            self.get_bullet_sound.play()
                            is_double_bullet = True
                            pygame.time.set_timer(DOUBLE_BULLET_TIME, 18 * 1000)#持续18s
                            bullet_supply.active = False

                    # 发射子弹
                    if not (delay % 10):#每颗子弹发射间隔
                        self.bullet_sound.play()
                        if is_double_bullet:
                            bullets = bullet2#当前要发射的子弹
                            bullets[bullet2_index].reset((me.rect.centerx - 33, me.rect.centery))#左边下一颗要发射的子弹
                            bullets[bullet2_index + 1].reset((me.rect.centerx + 30, me.rect.centery))#右边下一颗要发射的子弹
                            bullet2_index = (bullet2_index + 2) % BULLET2_NUM#更新要发射子弹的索引
                        else:
                            bullets = bullet1
                            bullets[bullet1_index].reset(me.rect.midtop)#下一颗要发射的子弹
                            bullet1_index = (bullet1_index + 1) % BULLET1_NUM#更新要发射子弹的索引

                    # 检测子弹是否击中敌机
                    for b in bullets:
                        if b.active:
                            b.move()#子弹移动
                            screen.blit(b.image, b.rect)#更新子弹位置
                            enemy_hit = pygame.sprite.spritecollide(b, enemies, False, pygame.sprite.collide_mask)#判断子弹group和enemyhgroup是否有碰撞
                            if enemy_hit:
                                b.active = False
                                for e in enemy_hit:#有enemy碰撞到子弹
                                    if e in mid_enemies or e in big_enemies:#中型敌机和大型敌机的处理
                                        e.hit = True#更改状态为被击中
                                        e.energy -= 1#减少energy
                                        if e.energy == 0:#energy为0，爆炸
                                            e.active = False
                                    else:
                                        e.active = False#小型敌机直接爆炸

                    # 绘制大型敌机
                    for each in big_enemies:
                        if each.active:
                            each.move()#移动
                            if each.hit:#大型敌机被击中
                                screen.blit(each.image_hit, each.rect)#更新被击中的位置，即显示被击中效果
                                each.hit = False
                            else:
                                if switch_image:#更换机体图片，实现一个动态的机尾喷射效果
                                    screen.blit(each.image1, each.rect)
                                else:
                                    screen.blit(each.image2, each.rect)

                            # 绘制血槽
                            pygame.draw.line(screen, BLACK, \
                                             (each.rect.left, each.rect.top - 5), \
                                             (each.rect.right, each.rect.top - 5), \
                                             2)#血槽位置，血槽宽度

                            # 当生命大于20%显示绿色，否则显示红色
                            energy_remain = each.energy / enemy.BigEnemy.energy
                            if energy_remain > 0.2:
                                energy_color = GREEN
                            else:
                                energy_color = RED
                            #绘制血量
                            pygame.draw.line(screen, energy_color, \
                                             (each.rect.left, each.rect.top - 5), \
                                             (each.rect.left + each.rect.width * energy_remain, \
                                              each.rect.top - 5), 2)

                            # 即将出现在画面中，播放音效
                            if each.rect.bottom == -50:
                                self.enemy3_fly_sound.play(-1)
                        else:
                            # 毁灭
                            if not (delay % 3):#延迟3ms
                                if e3_destroy_index == 0:
                                    self.enemy3_down_sound.play()
                                screen.blit(each.destroy_images[e3_destroy_index], each.rect)#更新被击中的动画效果
                                e3_destroy_index = (e3_destroy_index + 1) % 6#毁灭状态总共有6个步骤，依次更新
                                if e3_destroy_index == 0:
                                    self.enemy3_fly_sound.stop()#停止播放背景音
                                    score += 10000#得分
                                    each.reset()#重置大型敌机

                    # 绘制中型敌机：
                    for each in mid_enemies:
                        if each.active:
                            each.move()#中型敌机移动

                            if each.hit:#中型敌机被击中
                                screen.blit(each.image_hit, each.rect)#更新被击中的效果
                                each.hit = False#改变状态为被击中
                            else:
                                screen.blit(each.image, each.rect)

                            # 绘制血槽
                            pygame.draw.line(screen, BLACK, \
                                             (each.rect.left, each.rect.top - 5), \
                                             (each.rect.right, each.rect.top - 5), \
                                             2)
                            # 当生命大于20%显示绿色，否则显示红色
                            energy_remain = each.energy / enemy.MidEnemy.energy
                            if energy_remain > 0.2:
                                energy_color = GREEN
                            else:
                                energy_color = RED
                            pygame.draw.line(screen, energy_color, \
                                             (each.rect.left, each.rect.top - 5), \
                                             (each.rect.left + each.rect.width * energy_remain, \
                                              each.rect.top - 5), 2)
                        else:
                            # 毁灭
                            if not (delay % 3):
                                if e2_destroy_index == 0:
                                    self.enemy2_down_sound.play()
                                screen.blit(each.destroy_images[e2_destroy_index], each.rect)#更新图片
                                e2_destroy_index = (e2_destroy_index + 1) % 4#中型敌机的爆炸分为4个步骤，4个效果依次更新
                                if e2_destroy_index == 0:
                                    score += 6000#击败中型敌机的得分
                                    each.reset()

                    # 绘制小型敌机：
                    for each in small_enemies:
                        if each.active:
                            each.move()#小型敌机的移动
                            screen.blit(each.image, each.rect)#更新移动位置
                        else:
                            # 毁灭
                            if not (delay % 3):
                                if e1_destroy_index == 0:
                                    self.enemy1_down_sound.play()
                                screen.blit(each.destroy_images[e1_destroy_index], each.rect)#更新图片
                                e1_destroy_index = (e1_destroy_index + 1) % 4#小型敌机被击中分为4个步骤，4个效果依次更新
                                if e1_destroy_index == 0:
                                    score += 1000#击败小型敌机的得分
                                    each.reset()

                    # 检测我方飞机是否被撞与敌方飞机
                    enemies_down = pygame.sprite.spritecollide(me, enemies, False, pygame.sprite.collide_mask)
                    if enemies_down and not me.invincible:#如果相撞
                        me.active = False
                        for e in enemies_down:
                            e.active = False

                    # 绘制我方飞机
                    if me.active:
                        if switch_image:
                            screen.blit(me.image1, me.rect)
                        else:
                            screen.blit(me.image2, me.rect)
                    else:
                        # 毁灭
                        if not (delay % 3):
                            if me_destroy_index == 0:
                                self.me_down_sound.play()
                            screen.blit(me.destroy_images[me_destroy_index], me.rect)#更新我方飞机被撞的动画效果
                            me_destroy_index = (me_destroy_index + 1) % 4#动画效果总共有四个步骤
                            if me_destroy_index == 0:
                                life_num -= 1#生命条数-1
                                me.reset()#我方飞机重置，重新归位
                                pygame.time.set_timer(INVINCIBLE_TIME, 3 * 1000)#设置无敌状态事件

                    # 绘制全屏炸弹数量
                    bomb_text = bomb_font.render("× %d" % bomb_num, True, WHITE)
                    text_rect = bomb_text.get_rect()
                    screen.blit(bomb_image, (10, height - 10 - bomb_rect.height))
                    screen.blit(bomb_text, (20 + bomb_rect.width, height - 5 - text_rect.height))#更新炸弹数量

                    # 绘制剩余生命数量
                    if life_num:
                        for i in range(life_num):
                            screen.blit(life_image, \
                                        (width - 10 - (i + 1) * life_rect.width, \
                                         height - 10 - life_rect.height))

                    # 绘制得分
                    score_text = score_font.render("Score : %s" % str(score), True, WHITE)
                    screen.blit(score_text, (10, 5))#更新得分

                # 绘制游戏结束画面
                elif life_num == 0:
                    # 背景音乐停止
                    pygame.mixer.music.stop()

                    # 停止全部音效
                    pygame.mixer.stop()

                    # 停止发放补给
                    pygame.time.set_timer(SUPPLY_TIME, 0)

                    if not recorded:#保存本局游戏数据
                        recorded = True
                        game_time_end = time.time()  # 结束计时
                        game_time_duration = int(game_time_end - game_time_start)  # 运行所花时间
                        print(game_time_duration)

                        if self.game_mode =='easy':#按照游戏难度进行查询
                            socre_query_data = self.cursor.execute(
                                "select username,score from scores where mode='%s' order by score desc " % 'easy').fetchall()
                            if socre_query_data:
                                best_score = socre_query_data[0][1]
                                #查询当前游戏难度下的最高分
                                if score >best_score:
                                    best_score = score#更新最高分

                                self.cursor.execute("insert into scores (username,mode,score,duration) VALUES (?,?,?,?)",
                                                    (str(self.localuser), str(self.game_mode),int(score),int(game_time_duration)))#插入数据库
                                self.conn.commit()
                            else:
                                best_score = score
                                self.cursor.execute(
                                    "insert into scores (username,mode,score,duration) VALUES (?,?,?,?)",
                                    (str(self.localuser), str(self.game_mode), int(score),
                                     int(game_time_duration)))  # 插入数据库
                                self.conn.commit()

                        elif self.game_mode =='medium':
                            socre_query_data = self.cursor.execute(
                                "select username,score from scores where mode='%s' order by score desc " % 'medium').fetchall()
                            if socre_query_data:
                                best_score = socre_query_data[0][1]
                                # 查询当前游戏难度下的最高分
                                if score > best_score:
                                    best_score = score  # 更新最高分

                                self.cursor.execute(
                                    "insert into scores (username,mode,score,duration) VALUES (?,?,?,?)",
                                    (str(self.localuser), str(self.game_mode), int(score),
                                     int(game_time_duration)))  # 插入数据库
                                self.conn.commit()
                            else:
                                best_score = score
                                self.cursor.execute(
                                    "insert into scores (username,mode,score,duration) VALUES (?,?,?,?)",
                                    (str(self.localuser), str(self.game_mode), int(score),
                                     int(game_time_duration)))  # 插入数据库
                                self.conn.commit()
                        else:
                            socre_query_data = self.cursor.execute(
                                "select username,score from scores where mode='%s' order by score desc " % 'hard').fetchall()
                            if socre_query_data:
                                best_score = socre_query_data[0][1]
                                # 查询当前游戏难度下的最高分
                                if score > best_score:
                                    best_score = score  # 更新最高分

                                self.cursor.execute(
                                    "insert into scores (username,mode,score,duration) VALUES (?,?,?,?)",
                                    (str(self.localuser), str(self.game_mode), int(score),
                                     int(game_time_duration)))  # 插入数据库
                                self.conn.commit()
                            else:
                                best_score = score
                                self.cursor.execute(
                                    "insert into scores (username,mode,score,duration) VALUES (?,?,?,?)",
                                    (str(self.localuser), str(self.game_mode), int(score),
                                     int(game_time_duration)))  # 插入数据库
                                self.conn.commit()


                    # 绘制结束画面
                    record_score_text = score_font.render("Best: %d" % int(best_score), True, (255, 255, 255))
                    screen.blit(record_score_text, (50, 50))#显示Best

                    gameover_text1 = gameover_font.render("Your Score", True, (255, 255, 255))
                    gameover_text1_rect = gameover_text1.get_rect()
                    gameover_text1_rect.left, gameover_text1_rect.top = \
                        (width - gameover_text1_rect.width) // 2, height // 3
                    screen.blit(gameover_text1, gameover_text1_rect)#显示YourScore

                    gameover_text2 = gameover_font.render(str(score), True, (255, 255, 255))
                    gameover_text2_rect = gameover_text2.get_rect()
                    gameover_text2_rect.left, gameover_text2_rect.top = \
                        (width - gameover_text2_rect.width) // 2, \
                        gameover_text1_rect.bottom + 10
                    screen.blit(gameover_text2, gameover_text2_rect)#显示具体分数

                    again_rect.left, again_rect.top = \
                        (width - again_rect.width) // 2, \
                        gameover_text2_rect.bottom + 50
                    screen.blit(again_image, again_rect)#显示重新游戏按钮

                    gameover_rect.left, gameover_rect.top = \
                        (width - again_rect.width) // 2, \
                        again_rect.bottom + 10
                    screen.blit(gameover_image, gameover_rect)#显示游戏结束按钮

                    # 检测用户的鼠标操作
                    # 如果用户按下鼠标左键
                    if pygame.mouse.get_pressed()[0]:
                        # 获取鼠标坐标
                        pos = pygame.mouse.get_pos()
                        # 如果用户点击“重新开始”
                        #按钮左右之间，上下之间，判断落在内部
                        if again_rect.left < pos[0] < again_rect.right and \
                                again_rect.top < pos[1] < again_rect.bottom:
                            # 调用main函数，重新开始游戏
                            gaming()
                        # 如果用户点击“结束游戏”
                        elif gameover_rect.left < pos[0] < gameover_rect.right and \
                                gameover_rect.top < pos[1] < gameover_rect.bottom:

                            pygame.quit()
                            self.WelcomeWindow.show()


                            # 绘制暂停按钮
                screen.blit(paused_image, paused_rect)

                # 切换图片
                if not (delay % 5):
                    switch_image = not switch_image

                delay -= 1
                if not delay:
                    delay = 100

                pygame.display.flip()
                clock.tick(60)

        try:
            gaming()
        except SystemExit:
            #sys.exit(app.exec_())
            pygame.quit()
            self.WelcomeWindow.show()
        except:
            pygame.quit()
            self.WelcomeWindow.show()

    def scores_rank(self):
        #切换窗口
        self.WelcomeWindow.hide()
        self.RankingWindow.show()

        rank_easy_model = QStandardItemModel(3, 2)# 设置数据层次结构，3行2列，显示总榜top3
        rank_easy_model.setHorizontalHeaderLabels(['用户名', '分数(easy)'])# 设置水平方向头标签文本内容
        rank_medium_model = QStandardItemModel(3, 2)# 设置数据层次结构，3行2列，显示总榜top3

        rank_medium_model.setHorizontalHeaderLabels(['用户名', '分数(medium)'])# 设置水平方向头标签文本内容
        rank_hard_model = QStandardItemModel(3, 2)# 设置数据层次结构，3行2列，显示总榜top3
        rank_hard_model.setHorizontalHeaderLabels(['用户名', '分数(hard)'])# 设置水平方向头标签文本内容

        #查询数据
        rank_easy_query_data = self.cursor.execute("select username,score from scores where mode='%s' order by score desc " % 'easy').fetchall()
        rank_medium_query_data = self.cursor.execute("select username,score from scores where mode='%s' order by score desc " % 'medium').fetchall()
        rank_hard_query_data = self.cursor.execute("select username,score from scores where mode='%s' order by score desc " % 'hard').fetchall()
        #print(rank_easy_query_data)
        #装载数据
        if rank_easy_query_data:
            for row in range(min(len(rank_easy_query_data),3)):
                for column in range(2):
                    item = QStandardItem(str(rank_easy_query_data[row][column]))
                    # 设置每个位置的文本值
                    rank_easy_model.setItem(row, column, item)
        if rank_medium_query_data:
            for row in range(min(len(rank_medium_query_data),3)):
                for column in range(2):
                    item = QStandardItem(str(rank_medium_query_data[row][column]))
                    # 设置每个位置的文本值
                    rank_medium_model.setItem(row, column, item)
        if rank_hard_query_data:
            for row in range(min(len(rank_hard_query_data),3)):
                for column in range(2):
                    item = QStandardItem(str(rank_hard_query_data[row][column]))
                    # 设置每个位置的文本值
                    rank_hard_model.setItem(row, column, item)

        self.RankEasy.setModel(rank_easy_model)
        self.RankMedium.setModel(rank_medium_model)
        self.RankHard.setModel(rank_hard_model)

    def game_settings(self):

        self.WelcomeWindow.hide()
        self.SettingWindow.show()

    def back_welcome(self):

        self.SettingWindow.hide()
        self.WelcomeWindow.show()

    def back_welcome2(self):

        self.RankingWindow.hide()
        self.WelcomeWindow.show()

    def back_welcome3(self):

        self.GameWindow.hide()
        self.WelcomeWindow.show()

    def change_sound_status(self):
        #全局设置背景音乐
        #背景音乐开

        if self.sound_status =='on':
            icon = QtGui.QIcon()
            icon.addPixmap(QtGui.QPixmap(":/background/resources/icons/mute.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.SoundButton.setIcon(icon)
            self.sound_status = 'off'

        #背景音乐关
        else:
            icon = QtGui.QIcon()
            icon.addPixmap(QtGui.QPixmap(":/background/resources/icons/sound.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.SoundButton.setIcon(icon)
            self.sound_status = 'on'

    def change_sound_status2(self):
    #全局设置游戏音效
        #游戏音效开
        if self.sound_status2 =='on':
            icon = QtGui.QIcon()
            icon.addPixmap(QtGui.QPixmap(":/background/resources/icons/mute.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.SoundButton2.setIcon(icon)
            self.sound_status2 = 'off'
        #游戏音效关
        else:
            icon = QtGui.QIcon()
            icon.addPixmap(QtGui.QPixmap(":/background/resources/icons/sound.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.SoundButton2.setIcon(icon)
            self.sound_status2 = 'on'

    def change_volume_value(self):
        #调整游戏游戏背景音量
        self.background_music_volume= self.VolumeSlider.value()

    def change_volume_value2(self):
        #调整游戏音效音量
        self.game_sound_volume = self.VolumeSlider2.value()

    def game_mode_down(self):
        #调低游戏难度
        self.game_mode = self.game_modes[self.game_modes.index(self.GameMode.text())-1]
        self.GameMode.setText(self.game_mode)

    def game_mode_up(self):
        #调高游戏难度
        self.game_mode = self.game_modes[(self.game_modes.index(self.GameMode.text()) +1)%len(self.game_modes)]
        self.GameMode.setText(self.game_mode)

if __name__ == '__main__':


    if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
        QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
    if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
        QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)

    app = QtWidgets.QApplication(sys.argv)
    dk = app.desktop()
    my_pyqt_form = MyPyQT_Form()
    my_pyqt_form.move(dk.width() / 2 - my_pyqt_form.width() / 2, dk.height() / 2 - my_pyqt_form.height() / 2)
    my_pyqt_form.LoginWindow.show()
    sys.exit(app.exec_())

